﻿using MediatR;
using ProduceBasicData.Api.Application.Command.ProductionManage.Technology;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.ProductionManage.Technology
{
    public class CreateNodeCommandHandler : IRequestHandler<CreateNodeCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Nodeinfo> _noderespository;

        public CreateNodeCommandHandler(IBaseRespository<Nodeinfo> noderespository)
        {
            _noderespository = noderespository;
        }

        public async Task<ApiResult<int>> Handle(CreateNodeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>()
            {
                Code = ApiEnum.Success,
                Msg = "工单对应的工序"
            };

            try
            {
                // 【复杂业务验证逻辑】
                // 第一步：检查工序编号是否存在
                bool processIdExists = await _noderespository.AnyAsync(n =>
                    n.ProcessId == request.Id &&
                    !n.Isdel);

                if (processIdExists)
                {
                    // 第二步：如果工序编号存在，检查工单编号是否也存在
                    // 业务规则：同一工序可以用于不同工单，但不能在同一工单中重复使用
                    bool orderAndProcessExists = await _noderespository.AnyAsync(n =>
                        n.ProcessId == request.Id &&
                        n.OrderId == request.OrderId &&
                        !n.Isdel);

                    if (orderAndProcessExists)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = $"工序编号 {request.Id} 在工单 {request.OrderId} 中已存在，不能重复添加";
                        return result;
                    }

                    // 如果工序编号存在但工单编号不同，允许添加
                    // 这里不需要额外处理，直接继续到创建节点的逻辑
                }

                // 如果工序编号不存在，或者工序编号存在但工单编号不同，都可以添加

                DateTime date = DateTime.Now;
                var node = new Nodeinfo()
                {
                    NodeName = request.Processname,
                    ProcessId = request.Id,
                    OrderId = request.OrderId,
                    UserId = request.UserId,
                    UserName = request.UserName,
                    Processcode = request.Processcode,
                    PassStatus = 1, //工序通过
                    CreateName = request.UserName,
                    CreateTime = date,
                    Isdel = false,
                };

                result.Data = await _noderespository.AddAsync(node);
                result.Msg = "工单对应的工序添加成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"添加工序节点失败: {ex.Message}";
                result.Data = 0;
            }

            return await Task.FromResult(result);
        }
    }
}
